<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 用户信息卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <el-row :gutter="5">
        <!-- 输入框 -->
        <el-col :span="8">
          <el-input
            clearable
            placeholder="搜索用户名"
            v-model="queryParams.query"
            @clear="getUsersList()">
            <el-button slot="append" icon="el-icon-search" @click="sousuo"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="6">
          <el-button type="primary" @click="dialogFormVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户信息表格 -->
      <el-table :data="usersList" border style="width: 100%">
        <!-- 索引列 -->
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <!-- 用户名列 -->
        <el-table-column prop="username" label="姓名" width="100"></el-table-column>
        <!-- 邮箱列 -->
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <!-- 电话列 -->
        <el-table-column prop="mobile" label="电话" width="150"></el-table-column>
        <!-- 角色名称列 -->
        <el-table-column prop="role_name" label="角色" width="100"></el-table-column>
        <!-- 状态列 -->
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-row>
              <!-- 编辑按钮 -->
              <el-tooltip content="编辑用户" placement="top">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="showEditUser(scope.row.id)"></el-button>
              </el-tooltip>
              <!-- 删除按钮 -->
              <el-tooltip content="删除用户" placement="top">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteUser(scope.row.id)"></el-button>
              </el-tooltip>
              <!-- 设置角色 -->
              <el-tooltip content="设置角色" placement="top">
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-star-off"
                  circle
                  @click="showSetRole(scope.row)"></el-button>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页栏 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryParams.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"></el-pagination>
      </div>
    </el-card>

    <!-- 添加用户弹框 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <!-- 用户弹框表单 -->
      <el-form :model="addUserForm" :rules="rules" ref="addUserFormRef">
        <!-- 用户名称 -->
        <el-form-item label="用户名称" :label-width="formLabelWidth" prop="username">
          <el-input
            v-model="addUserForm.username"
            clearable
            placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <!-- 用户密码 -->
        <el-form-item label="用户密码" :label-width="formLabelWidth" prop="password">
          <el-input
            v-model="addUserForm.password"
            clearable
            show-password
            placeholder="请输入用户密码"></el-input>
        </el-form-item>
        <!-- 用户邮箱 -->
        <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="addUserForm.email" clearable placeholder="请输入用户邮箱"></el-input>
        </el-form-item>
        <!-- 用户电话 -->
        <el-form-item label="用户电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="addUserForm.mobile" clearable placeholder="请输入用户电话"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser()">添 加</el-button>
      </div>
    </el-dialog>

    <!-- 编辑用户弹框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible">
      <!-- 用户弹框表单 -->
      <el-form :model="editUserForm" :rules="rules" ref="editUserFormRef">
        <!-- 用户名称 -->
        <el-form-item label="用户名称" :label-width="formLabelWidth">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <!-- 用户邮箱 -->
        <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="email">
          <el-input v-model="editUserForm.email" clearable></el-input>
        </el-form-item>
        <!-- 用户电话 -->
        <el-form-item label="用户电话" :label-width="formLabelWidth" prop="mobile">
          <el-input v-model="editUserForm.mobile" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(ediId)">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 设置角色对话框 -->
    <el-dialog title="设置角色" :visible.sync="setRolDialogVisible" width="400px">
      <div>
        <p>当前用户名称：{{ userInfo.username }}</p>
        <p>当前用户角色：{{ userInfo.role_name }}</p>
        <p>
          设置用户角色:
          <el-select v-model="selectId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="setRolDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 手机号校验规则
    const checkMobile = (rule, value, cb) => {
      let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (reg.test(value)) {
        return cb()
      }
      cb(new Error('手机号码格式不正确'))
    }
    // 邮箱正则表达式
    const checkEmail = (rule, value, callback) => {
      let regEmail = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    return {
      // 用户信息列表
      usersList: [],
      // 角色列表
      rolesList: [],
      // 请求参数
      queryParams: {
        // 查询条件
        query: '',
        // 请求多少页
        pagenum: 1,
        // 请求每页多少条
        pagesize: 2
      },
      // 总数
      total: 0,
      // 是否显示添加用户弹框
      dialogFormVisible: false,
      // 是否显示编辑用户弹框
      editDialogVisible: false,
      // 是否显示设置角色对话框
      setRolDialogVisible: false,
      // 添加用户弹窗表单信息
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 编辑用户弹窗表单信息
      editUserForm: {
        id: '',
        role_id: '',
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 要编辑的用户ID
      ediId: '',
      // 弹窗表单宽度
      formLabelWidth: '100px',
      // 用户表单校验规则
      rules: {
        username: [
          { required: true, message: '请输入3-10位字符的用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '请输入3-10位字符的用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入6-16位字符的密码', trigger: 'blur' },
          { min: 6, max: 16, message: '请输入6-16位字符的密码', trigger: 'blur' }
        ],
        email: [{ validator: checkEmail, trigger: 'blur' }],
        mobile: [{ validator: checkMobile, trigger: 'blur' }]
      },
      // 需要设置角色的用户信息
      userInfo: {},
      // 设置角色选择的id
      selectId: ''
    }
  },
  created() {
    this.getUsersList()
  },
  updated() {
    // this.getUsersList()
  },
  methods: {
    // 请求用户列表数据
    async getUsersList() {
      const { data: res } = await this.$http.get('users', { params: this.queryParams })
      // console.log(res);
      if (res.meta.status !== 200) return res.meta.msg
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // 请求角色列表数据（含权限数据）
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.mate.msg)
      // console.log(res)
      this.rolesList = res.data
    },
    // 提交添加用户
    addUser() {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addUserForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败!')
        this.$message.success('添加用户成功')
        this.dialogFormVisible = false
        this.getUsersList()
      })
    },
    // 改变用户状态
    async changeState(user) {
      // console.log(user);
      const { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if (res.meta.status !== 200) return this.$message.error('修改状态失败!')
      this.$message.success(res.meta.msg)
    },
    // 根据 ID 请求用户数据方法
    async getUserById(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editUserForm = res.data
    },
    // 显示编辑用户弹窗
    showEditUser(uid) {
      // console.log(uid)
      this.getUserById(uid)
      this.editDialogVisible = true
    },
    // 提交编辑用户
    editUser(uid) {
      this.$refs.editUserFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`users/${uid}`, this.editUserForm)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('编辑用户失败!')
        this.$message.success('更新成功！')
        this.dialogFormVisible = false
        this.getUsersList()
      })
    },
    // 删除用户
    deleteUser(uid) {
      // console.log(uid)
      // 警告删除
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${uid}`)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.getUsersList()
        })
        .catch(() => this.$message.info('已取消删除'))
    },
    // 显示设置用户角色对话框
    async showSetRole(userInfo) {
      // console.log(userInfo)
      this.getRolesList()
      this.userInfo = userInfo
      this.setRolDialogVisible = true
      // getUserById(uid)
    },
    // 提交设置角色信息
    async setRoles() {
      // console.log('11')
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectId
      })
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.userInfo = res.data
      this.setRolDialogVisible = false
      this.getUsersList()
    },
    // 无论是搜索用户，还是跳转页面，其实都是改变一下请求参数，因此请求方法只需要写一次
    // 搜索用户
    async sousuo() {
      this.getUsersList()
    },
    // 改变每页显示条数
    handleSizeChange(newSize) {
      this.queryParams.pagesize = newSize
      this.getUsersList()
    },
    // 跳转到哪一页
    handleCurrentChange(val) {
      this.queryParams.pagenum = val
      this.getUsersList()
    }
  }
}
</script>

<style>
.box-card {
  margin-top: 15px;
}

.el-table {
  margin-top: 5px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
</style>
